package de.kardass.jsmatep.in.reader;

import java.util.Arrays;
import java.util.List;

public class CsvBufferedRecordSplitted {

	private static final char LOCAL_RECORD_TERMINATOR_1 = '@';
	private static final char LOCAL_RECORD_TERMINATOR_2 = '~';
	
	private static String lastReadRecord = null;
	private static List<String> lastParsedValues;
	
	public String readField(final String aString, final String deliminator, final int fieldNo) {
		return splittStringToRecord(aString, deliminator).get(fieldNo);
	}

	public List<String> splittStringToRecord(final String aString, final String deliminator) {
		if (!isSameRecord(aString)) {
			lastParsedValues = splittedRead(aString, deliminator);
			lastReadRecord = aString;
		}
		return lastParsedValues;
	}

	private boolean isSameRecord(String aRecord) {
		return aRecord.equals(lastReadRecord);
	}

	public String getLastReadRecord() {
		return lastReadRecord;
	}
	
	private static List<String> splittedRead(final String aString, final String delim) {
		final char localRecordTerminator = 
			delim.equals(LOCAL_RECORD_TERMINATOR_1) ? LOCAL_RECORD_TERMINATOR_2 : LOCAL_RECORD_TERMINATOR_1;
//		System.out.println("text:        " + aString);
//		System.out.println("delim:       " + delim);
//		System.out.println("local term:  " + localRecordTerminator);
		final String parsableString = aString + delim + localRecordTerminator;;
//		System.out.println("corrected text:  " + parsableString);
		final String [] lineTwoSplit = parsableString.split(delim);
		final String [] finalResult = new String [lineTwoSplit.length-1];
		System.arraycopy(lineTwoSplit, 0, finalResult, 0, lineTwoSplit.length-1);
//		for (int i = 0; i < finalResult.length; i++) {
//			System.out.println(i + " -> " + finalResult[i]);
//		};
//		System.out.println("=> length: " + finalResult.length);
		return Arrays.asList(finalResult);
	}

}
